<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use App\Models\SeckillProduct;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Cache;
use App\Services\MakeSeckillOrder\MakeSeckillOrderRequest;
use App\Services\MakeSeckillOrder\ConfirmSeckillOrderRequest;


class SeckillProductsController extends Controller
{
	/*public function __construct()
	{
       
		$this->middleware('random.drop.storm:50')->only('store');
	}
*/
	

	public function index()
	{
		$province = request('province');
		$products = SeckillProduct::getProducts($province,0);
		return response()->json($products);
	}

	public function new()
	{
		$province = request('province');
		$products = SeckillProduct::getProducts($province,1);
		return response()->json($products);
	}


	public function info()
	{
		$strat_at = cs("good")->start_at;
		$end_at = cs("good")->end_at;

		$result = [
			'seckill_range_time' => $strat_at."-".$end_at,
			'today_start_at' =>  date("Y-m-d",time()).' '.$strat_at,
			'today_end_at' => date("Y-m-d",time()).' '.$end_at,

		];
		return response()->json($result);
	}

	public function store()
	{
		$lock = Cache::lock('buy_seckill_product', 15);

		try {

			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(MakeSeckillOrderRequest::class);

			$uid = $request->user()->id;
			$sid = $request->sid;
			
			if (SeckillProduct::sIsInSoldCache($sid)) {
				SeckillProduct::sBuyFromCache($uid, $sid);
			}

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}

	

	

	
}
